package com.mty.kjtest.Presenter;

import android.content.Context;
import com.mty.kjtest.Http.HttpMethods;
import com.mty.kjtest.MVPView.IUserLoginView;
import com.mty.kjtest.Model.User;
import com.mty.kjtest.Rxjava.ProgressSubscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 天宇 on 2017/7/2.
 */
public class UserLoginPresenter {

    private User user;
    private IUserLoginView userLoginView;
    private Context context;

    public UserLoginPresenter(IUserLoginView userLoginView, Context context) {
        this.userLoginView = userLoginView;
        this.context = context;
    }

    public void login() {
        HttpMethods.getInstance()
                   .getNetwork()
                   .getTestModel(userLoginView.getUserName(), userLoginView.getPassword())
                   .subscribeOn(Schedulers.io())
                   .observeOn(AndroidSchedulers.mainThread())
                   .subscribe(new ProgressSubscriber<User>(new ProgressSubscriber.SubscriberOnNextListener<User>() {
                       @Override
                       public void onNext(User user) {
                           userLoginView.toMainActivity(user);
                       }
                   }, new ProgressSubscriber.SubscriberonErrorListener() {
                       @Override
                       public void onError(Throwable e) {
                           userLoginView.showFailedError();
                           clear();
                       }
                   }, context));
    }

    public void clear() {
        userLoginView.clearUserName();
        userLoginView.clearPassword();
    }
}
